package com.itwill.ecom.member;

import java.sql.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/member")
public class MemberController {	
	
	@Autowired MemberService memberService;
	
	public MemberController() {
		System.out.println("△MemberController 생성자△");
	}
	
	//member JSON(get_memberJson.jsp 안쓰이는데 알아두면 좋을 것 같아서 냅둠)
	@RequestMapping("/getmemberJSON")
	public String getMemberJSON(){
		System.out.println("△getmemberJSON요청△");
		return "member/get_memberJSON";
	}

	//member list JSON(get_memberlistJson.jsp 안쓰이는데 알아두면 좋을 것 같아서 냅둠)
	@RequestMapping("/getmemberlistJSON")
	public String getMemberListJSON(){
		System.out.println("△getmemberlistJSON요청△");
		return "member/get_memberlistJSON";
	}
	
	//ajax (반환타입앞에 @ResponseBody를 선언해서 컬백 인자에 객체로 넘기는것을 알린다??)
	@RequestMapping("/getajaxmemberbeans")
	public @ResponseBody List<MemberBeans> getAjaxMemberBeans(){
		
		System.out.println("△getajaxmemberbeans요청△");
		try{
			List<MemberBeans> memberBeansList = memberService.getMemberList();
			return memberBeansList;
		}
		catch(Exception e){
			System.out.println("getajaxmemberbeans HttpServlet Exception");
			return null;
		}
	}

	//join_form
	@RequestMapping("/joinform")
	public String joinForm(HttpSession session){
		
		System.out.println("△joinform요청△");
		
		try{
			//세션이 잡혀있을 때(로그인중일때) joinform 요청한다면...
			String sid = (String)session.getAttribute("sid");
			if(sid != null){
				return "redirect:/";
			}
			return "member/join_form";
		}
		catch(Exception e){
			System.out.println("joinform HttpServlet Exception");
			return "redirect:/";
		}
		
	}

	//join_action
	@RequestMapping("/joinaction")
	public String joinAction(@ModelAttribute MemberBeans memberBeans, @RequestParam("member_yyyy") int member_yyyy,
					@RequestParam("member_mm") int member_mm,  @RequestParam("member_dd") int member_dd,
					@RequestParam("member_zipcode1") String member_zipCode1, @RequestParam("member_zipcode2") String member_zipCode2,
					HttpServletRequest request){

		System.out.println("△joinaction요청△");
		
		try{
			request.setCharacterEncoding("utf-8");
			
			final int minusyyyy = 1900; //sql.Date.class 에서 1900년을 기본으로 더하게 되있음
			Date member_birth = new Date(member_yyyy-minusyyyy, member_mm-1,member_dd);
			memberBeans.setMember_birth(member_birth);
			
			String member_zip = member_zipCode1 + "-" + member_zipCode2;
			memberBeans.setMember_zip(member_zip);
			
			memberBeans.setMember_password(encryptPassword(memberBeans.getMember_password()));
			
			memberBeans.setMember_grade(1);//0:Admin, 1:일반회원(회원가입시 지정등급), 2:제제상태
			
			memberService.createMember(memberBeans);
			
			return "redirect:loginform?result=1";
		}
		catch (Exception e){
			System.out.println("joinaction HttpServlet Exception");
			return "redirect:/";
		}

	}

	//login_form
	@RequestMapping("/loginform")
	public String loginForm(HttpSession session){
		
		System.out.println("△loginform요청△");
		
		try{
			//세션이 잡혀있을 때(로그인중일때) loginform 요청한다면...
			String sid = (String)session.getAttribute("sid");
			if(sid != null){
				return "redirect:/";
			}
		
			return "member/login_form";
		}
		catch(Exception e){
			System.out.println("loginform HttpServlet Exception");
			return "redirect:/";
		}
		
	}

	//login_action
	@RequestMapping("/loginaction")
	public String loginAction(HttpServletRequest request, HttpSession session){
		
		System.out.println("△loginaction요청△");
		
		try{
			request.setCharacterEncoding("utf-8");
			String logout = request.getParameter("logout");
			String p_id = request.getParameter("member_id");
			String p_password = request.getParameter("member_password");
			
			//로그아웃 처리
			if(logout != null){
				session.removeAttribute("sno");
				session.removeAttribute("sid");
				session.removeAttribute("admin");
				return "redirect:/";
			}
			
			//로그인 처리
			List<MemberBeans> memberBeansList = memberService.getMemberList();
			
			//getParameter
			int result=0; //(로그인실패0, 로그인성공1)
			int p_no=0;
			
			MemberBeans temp = memberService.getMemberById(p_id);
			if(temp!=null){
				p_no = temp.getMember_no(); //성오형 요청
			}
			
			/***** 비지니스시작****/			
			for(MemberBeans memberBeans : memberBeansList){ //아이디와 패스워드 비교 
				if(memberBeans.getMember_id().equals(p_id) && decryptPassword(memberBeans.getMember_password()).equals(p_password)){
					result=1;
					if(memberBeans.getMember_grade()==0){ //관리자라면??
						result=2;
						break;
					}
					break;
				}
			}
			
			if(result==0){ //로그인실패
				return "redirect:loginform?result="+result;
			}
			else if(result==1){ //로그인성공
				result=0;
				session.setAttribute("sno", p_no);
				session.setAttribute("sid", p_id); //아이디 세션등록
				return "redirect:/";
			}
			else if(result==2){ //관리자로그인성공
				result=0;
				session.setAttribute("sno", p_no);
				session.setAttribute("sid", p_id); //아이디 세션등록
				session.setAttribute("admin", true);
				return "redirect:/";
			}
			
			return "redirect:/";
		}
		catch(Exception e){
			System.out.println("loginaction HttpServlet Exception");
			return "redirect:/";
		}
	}

	//modify_form
	@RequestMapping("/modifyform")
	public String modifyForm(Model model, HttpServletRequest request, HttpSession session){
		System.out.println("△modifyform요청△");
		
		try{
			request.setCharacterEncoding("utf-8");
			
			//세션이 없을 때(로그인 안한상태일때) modifyform 요청한다면...
			String sid = (String)session.getAttribute("sid");
			if(sid == null){
				return "redirect:loginform";
			}
			
			//Birth 자르는 부분
			MemberBeans memberBeans = memberService.getMemberById(sid);
			Date D_birth = memberBeans.getMember_birth();
			String birth = String.valueOf(D_birth);
			String year = birth.substring(0, 4);
			String month = birth.substring(5, 7);
			if(month.charAt(0)=='0'){
				month = String.valueOf(month.charAt(1)); //01~09로 들어오는 월값의 0을 제거하기 위함
			}
			String day = birth.substring(8, 10);
			if(day.charAt(0)=='0'){
				day = String.valueOf(day.charAt(1)); //01~09로 들어오는 일값의 0을 제거하기 위함
			}
			//ZipCode 자르는 부분
			String zipCode = memberBeans.getMember_zip();
			String zipCode1 = zipCode.substring(0, 3);
			String zipCode2 = zipCode.substring(4, 7);
			
			//model로 싣든 request로 싣든 EL로 받는데는 아무거나 상관없이 똑같이 받음
			model.addAttribute("memberBeans", memberBeans);
			model.addAttribute("member_year", year);
			model.addAttribute("member_month", month);
			model.addAttribute("member_day", day);
			model.addAttribute("member_zipCode1", zipCode1);
			model.addAttribute("member_zipCode2", zipCode2);
			/*
			request.setAttribute("memberBeans", memberBeans);
			request.setAttribute("member_birth", birth);
			request.setAttribute("member_year", year);
			request.setAttribute("member_month", month);
			request.setAttribute("member_day", day);
			request.setAttribute("member_zipCode1", zipCode1);
			request.setAttribute("member_zipCode2", zipCode2);
			*/
			
			return "member/modify_form";
		}
		catch(Exception e){
			System.out.println("modifyform HttpServlet Exception");
			return "redirect:/";
		}
		
	}

	//modify_action
	@RequestMapping("/modifyaction")
	public String modifyAction(@ModelAttribute MemberBeans memberBeans, @RequestParam("member_yyyy") int member_yyyy,
			@RequestParam("member_mm") int member_mm,  @RequestParam("member_dd") int member_dd,
			@RequestParam("member_zipcode1") String member_zipCode1, @RequestParam("member_zipcode2") String member_zipCode2,
			HttpServletRequest request, Model model){

		System.out.println("△modifyaction요청△");

		try{
			request.setCharacterEncoding("utf-8");
			
			//수정된 memberBeans 완성되는 부분
			final int minusyyyy = 1900; //sql.Date.class 에서 1900년을 기본으로 더하게 되있음
			Date member_birth = new Date(member_yyyy-minusyyyy, member_mm-1,member_dd);
			memberBeans.setMember_birth(member_birth);
			
			String member_zip = member_zipCode1 + "-" + member_zipCode2;
			memberBeans.setMember_zip(member_zip);
			
			/*******************************************************************************/

			/* @Anotation으로 Form 에서 Bean 받아오면 No 자체가 없음(SQL오류도 안뜨고 실수 X)
			 * 또 조심해야될 점은 <input>에서 값을 활용할때는 disabled 하면 아예 값이 안먹힘
			 * 그래서 출력만을 위한다면 disabled 하고 값을 써야되면 readonly 로 해라(개고생함)
			 */
			int member_no = memberService.getMemberById(memberBeans.getMember_id()).getMember_no();
			int member_grade = memberService.getMemberById(memberBeans.getMember_id()).getMember_grade();
			
			memberBeans.setMember_no(member_no);
			memberBeans.setMember_grade(member_grade);
			
			/*******************************************************************************/
						
			//실어보내는 부분
			//model로 싣든 request로 싣든 EL로 받는데는 아무거나 상관없이 똑같이 받음
			model.addAttribute("memberBeans", memberBeans);
			model.addAttribute("member_year", member_yyyy);
			model.addAttribute("member_month", member_mm);
			model.addAttribute("member_day", member_dd);
			model.addAttribute("member_zipCode1", member_zipCode1);
			model.addAttribute("member_zipCode2", member_zipCode2);
			/*
			request.setAttribute("memberBeans", memberBeans);
			request.setAttribute("member_birth", birth);
			request.setAttribute("member_year", year);
			request.setAttribute("member_month", month);
			request.setAttribute("member_day", day);
			request.setAttribute("member_zipCode1", zipCode1);
			request.setAttribute("member_zipCode2", zipCode2);
			*/
			
			memberService.updateMember(memberBeans);
			
			return "redirect:modifyform?result=1";
		}
		catch(Exception e){
			System.out.println("modifyaction HttpServlet Exception");
			return "redirect:/";
		}

	}

	//delete_action
	@RequestMapping("/deleteaction")
	public String deleteAction(HttpServletRequest request, HttpSession session){
		
		System.out.println("△deleteaction요청△");

		try{
			request.setCharacterEncoding("utf-8");
			
			String m_id = String.valueOf(session.getAttribute("sid")); 
			
			session.removeAttribute("sno"); //성오형요청 session 지우기
			session.removeAttribute("sid");
			MemberBeans memberBeans = memberService.getMemberById(m_id);
			memberService.deleteMember(memberBeans);
			
			return "redirect:loginform";
		}
		catch (Exception e){
			System.out.println("deleteaction HttpServlet Exception");
			return "redirect:/";
		}
	}
	
	
	
	
	
	// String Data Password Encrypt, Decrypt (아트배쉬 -> 시저스사이퍼-3)
	// Encrypt Password
	public String encryptPassword(String pw){
		String encPw = ""; // 암호화된 패스워드를 저장할 스트링 데이터
		
		for(int i = 0 ; i < pw.length() ; i++){ // 입력으로 들어온 패스워드를 한글자씩 순회 
			char c = pw.charAt(i);
			
			if(c >= 'a' && c <= 'z'){ // 영문 소문자인 경우  
				c = (char)('a' + 'z' - (int)c);
				c = (char)((int)c + 3);
				if(c > 'z') c -= ('z' - 'a' + 1);
			}
			
			else if(c >= 'A' && c <= 'Z'){ // 영문 대문자인 경우
				c = (char)('A' + 'Z' - (int)c);
				c = (char)((int)c + 3);
				if(c > 'Z') c -= ('Z' - 'A' + 1);
			}
			
			else if(c >= '0' && c <= '9'){ // 숫자인 경우
				c = (char)('0' + '9' - (int)c);
				c = (char)((int)c + 3);
				if(c > '9') c -= ('9' - '0' + 1);
			}
			
			encPw += c;
		}
		
		return encPw;
	}
	
	// DecryptPassword
	public String decryptPassword(String pw){
		String decPw = "";
		
		for(int i = 0 ; i < pw.length() ; i++){
			char c = pw.charAt(i);
			
			if(c >= 'a' && c <= 'z'){ // 영문 소문자인 경우  
				c = (char)((int)c - 3);
				if(c < 'a') c += ('z' - 'a' + 1);
				c = (char)('a' + 'z' - (int)c);
			}
			
			else if(c >= 'A' && c <= 'Z'){ // 영문 대문자인 경우
				c = (char)((int)c - 3);
				if(c < 'A') c += ('Z' - 'A' + 1);
				c = (char)('A' + 'Z' - (int)c);
			}
			
			else if(c >= '0' && c <= '9'){ // 숫자인 경우
				c = (char)((int)c - 3);
				if(c < '0') c += ('9' - '0' + 1);
				c = (char)('0' + '9' - (int)c);
			}
			
			decPw += c;
		}
		
		return decPw;
	}
}
